package com.example.pceb.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pceb.entity.SchoolEnterpriseCooperation;
import com.example.pceb.mapper.SchoolEnterpriseCooperationMapper;
import com.example.pceb.service.CooperationService;
import com.example.pceb.VO.ProjectProgressVO;
import com.example.pceb.entity.ProjectPhaseInitiation;
import com.example.pceb.entity.ProjectPhaseContract;
import com.example.pceb.entity.ProjectPhaseStart;
import com.example.pceb.entity.ProjectPhaseMidterm;
import com.example.pceb.entity.ProjectPhaseCompletion;
import com.example.pceb.mapper.ProjectPhaseInitiationMapper;
import com.example.pceb.mapper.ProjectPhaseContractMapper;
import com.example.pceb.mapper.ProjectPhaseStartMapper;
import com.example.pceb.mapper.ProjectPhaseMidtermMapper;
import com.example.pceb.mapper.ProjectPhaseCompletionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.pceb.VO.ProjectPhaseUpdateRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.util.List;
import com.example.pceb.mapper.EnterpriseMapper;
import com.example.pceb.mapper.SchoolAdminMapper;
import com.example.pceb.mapper.SchoolMapper;
import com.example.pceb.entity.Enterprise;
import com.example.pceb.entity.SchoolAdmin;
import com.example.pceb.entity.School;

@Service
public class CooperationServiceImpl implements CooperationService {

    @Autowired
    private SchoolEnterpriseCooperationMapper cooperationMapper;

    @Autowired
    private ProjectPhaseInitiationMapper initiationMapper;

    @Autowired
    private ProjectPhaseContractMapper contractMapper;

    @Autowired
    private ProjectPhaseStartMapper startMapper;

    @Autowired
    private ProjectPhaseMidtermMapper midtermMapper;

    @Autowired
    private ProjectPhaseCompletionMapper completionMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private SchoolAdminMapper schoolAdminMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Override
    public List<SchoolEnterpriseCooperation> listCooperationProjects(String userType) {
        String publisherType = "school".equals(userType) ? "企业" : "学校";
        QueryWrapper<SchoolEnterpriseCooperation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publisher_type", publisherType);
        return cooperationMapper.selectList(queryWrapper);
    }

    @Override
    public SchoolEnterpriseCooperation getCooperationDetail(Long id) {
        return cooperationMapper.selectById(id);
    }

    @Override
    public List<ProjectProgressVO> getProjectProgress(Long projectId) {
        List<ProjectProgressVO> progressList = new java.util.ArrayList<>();
        // 1. 立项阶段
        ProjectPhaseInitiation initiation = initiationMapper.selectByProjectId(projectId);
        ProjectProgressVO vo1 = new ProjectProgressVO();
        vo1.setTitle("项目立项");
        vo1.setType("success");
        if (initiation != null) {
            vo1.setStatus(initiation.getStatus());
            vo1.setResponsiblePerson(initiation.getResponsiblePerson());
            vo1.setStartTime(initiation.getStartTime());
            vo1.setDescription(initiation.getDescription());
        }
        progressList.add(vo1);
        // 2. 合同签署
        ProjectPhaseContract contract = contractMapper.selectByProjectId(projectId);
        ProjectProgressVO vo2 = new ProjectProgressVO();
        vo2.setTitle("合作协议签署");
        vo2.setType("success");
        if (contract != null) {
            vo2.setStatus(contract.getStatus());
            vo2.setResponsiblePerson(contract.getResponsiblePerson());
            vo2.setStartTime(contract.getStartTime());
            vo2.setDescription(contract.getDescription());
        }
        progressList.add(vo2);
        // 3. 项目启动
        ProjectPhaseStart start = startMapper.selectByProjectId(projectId);
        ProjectProgressVO vo3 = new ProjectProgressVO();
        vo3.setTitle("项目启动");
        vo3.setType("primary");
        if (start != null) {
            vo3.setStatus(start.getStatus());
            vo3.setResponsiblePerson(start.getResponsiblePerson());
            vo3.setStartTime(start.getStartTime());
            vo3.setDescription(start.getDescription());
        }
        progressList.add(vo3);
        // 4. 中期检查
        ProjectPhaseMidterm midterm = midtermMapper.selectByProjectId(projectId);
        ProjectProgressVO vo4 = new ProjectProgressVO();
        vo4.setTitle("中期检查");
        vo4.setType("warning");
        if (midterm != null) {
            vo4.setStatus(midterm.getStatus());
            vo4.setResponsiblePerson(midterm.getResponsiblePerson());
            vo4.setStartTime(midterm.getStartTime());
            vo4.setDescription(midterm.getDescription());
        }
        progressList.add(vo4);
        // 5. 结项
        ProjectPhaseCompletion completion = completionMapper.selectByProjectId(projectId);
        ProjectProgressVO vo5 = new ProjectProgressVO();
        vo5.setTitle("项目结项");
        vo5.setType("info");
        if (completion != null) {
            vo5.setStatus(completion.getStatus());
            vo5.setResponsiblePerson(completion.getResponsiblePerson());
            vo5.setStartTime(completion.getStartTime());
            vo5.setDescription(completion.getDescription());
        }
        progressList.add(vo5);
        return progressList;
    }

    @Override
    public boolean saveCooperation(SchoolEnterpriseCooperation cooperation) {
        return cooperationMapper.insert(cooperation) > 0;
    }

    @Override
    public List<SchoolEnterpriseCooperation> listByPublisherType(String publisherType, String projectStatus) {
        QueryWrapper<SchoolEnterpriseCooperation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publisher_type", publisherType);
        queryWrapper.eq("project_status", projectStatus);
        return cooperationMapper.selectList(queryWrapper);
    }

    @Override
    public SchoolEnterpriseCooperation getById(Long id) {
        return cooperationMapper.selectById(id);
    }

    @Override
    public List<SchoolEnterpriseCooperation> getMyProjects(String username, String userType) {
        QueryWrapper<SchoolEnterpriseCooperation> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("project_status", "未立项");
        if ("enterprise".equals(userType)) {
            // 通过enterprise表查出企业名称
            String enterpriseName = enterpriseMapper.selectEnterpriseNameByUsername(username);
            if (enterpriseName != null && !enterpriseName.isEmpty()) {
                queryWrapper.eq("enterprise_name", enterpriseName);
            } else {
                // 查不到企业信息，返回空
                return java.util.Collections.emptyList();
            }
        } else if ("school".equals(userType)) {
            // 通过school_admin表查school_id，再查school表查schoolName
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SchoolAdmin> adminQuery = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            adminQuery.eq("username", username);
            SchoolAdmin admin = schoolAdminMapper.selectOne(adminQuery);
            if (admin != null && admin.getSchoolId() != null) {
                School school = schoolMapper.selectById(admin.getSchoolId());
                if (school != null && school.getSchoolName() != null) {
                    queryWrapper.eq("school_name", school.getSchoolName());
                } else {
                    return java.util.Collections.emptyList();
                }
            } else {
                return java.util.Collections.emptyList();
            }
        }
        return cooperationMapper.selectList(queryWrapper);
    }

    @Override
    public List<SchoolEnterpriseCooperation> getSchoolAdminPendingProjects(String username) {
        QueryWrapper<SchoolEnterpriseCooperation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publisher_username", username);
        queryWrapper.ne("project_status", "未立项");
        return cooperationMapper.selectList(queryWrapper);
    }

    @Override
    public List<SchoolEnterpriseCooperation> getEnterpriseAdminPendingProjects(String username) {
        QueryWrapper<SchoolEnterpriseCooperation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publisher_username", username);
        queryWrapper.ne("project_status", "未立项");
        return cooperationMapper.selectList(queryWrapper);
    }

    @Override
    public boolean deleteProject(Long id, String publisherUsername) {
        return cooperationMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateProjectPhase(ProjectPhaseUpdateRequest request) {
        try {
            String phaseType = request.getPhaseType();
            Date startTime = null;
            if (request.getStartTime() != null && !request.getStartTime().isEmpty()) {
                String s = request.getStartTime().replace("T", " ").split(" ")[0];
                startTime = new SimpleDateFormat("yyyy-MM-dd").parse(s);
            }
            
            System.out.println("更新项目阶段信息: " + request.getProjectId() + ", 阶段类型: " + phaseType);
            
            switch (phaseType) {
                case "initiation":
                    ProjectPhaseInitiation initiation = new ProjectPhaseInitiation();
                    initiation.setProjectId(request.getProjectId());
                    initiation.setStatus(request.getStatus());
                    initiation.setResponsiblePerson(request.getResponsiblePerson());
                    initiation.setStartTime(startTime);
                    initiation.setDescription(request.getDescription());
                    int result1 = initiationMapper.updateByProjectId(initiation);
                    System.out.println("立项阶段更新结果: " + result1);
                    break;
                case "contract":
                    ProjectPhaseContract contract = new ProjectPhaseContract();
                    contract.setProjectId(request.getProjectId());
                    contract.setStatus(request.getStatus());
                    contract.setResponsiblePerson(request.getResponsiblePerson());
                    contract.setStartTime(startTime);
                    contract.setDescription(request.getDescription());
                    int result2 = contractMapper.updateByProjectId(contract);
                    System.out.println("合同阶段更新结果: " + result2);
                    break;
                case "start":
                    ProjectPhaseStart start = new ProjectPhaseStart();
                    start.setProjectId(request.getProjectId());
                    start.setStatus(request.getStatus());
                    start.setResponsiblePerson(request.getResponsiblePerson());
                    start.setStartTime(startTime);
                    start.setDescription(request.getDescription());
                    int result3 = startMapper.updateByProjectId(start);
                    System.out.println("启动阶段更新结果: " + result3);
                    break;
                case "midterm":
                    ProjectPhaseMidterm midterm = new ProjectPhaseMidterm();
                    midterm.setProjectId(request.getProjectId());
                    midterm.setStatus(request.getStatus());
                    midterm.setResponsiblePerson(request.getResponsiblePerson());
                    midterm.setStartTime(startTime);
                    midterm.setDescription(request.getDescription());
                    int result4 = midtermMapper.updateByProjectId(midterm);
                    System.out.println("中期阶段更新结果: " + result4);
                    break;
                case "completion":
                    ProjectPhaseCompletion completion = new ProjectPhaseCompletion();
                    completion.setProjectId(request.getProjectId());
                    completion.setStatus(request.getStatus());
                    completion.setResponsiblePerson(request.getResponsiblePerson());
                    completion.setStartTime(startTime);
                    completion.setDescription(request.getDescription());
                    int result5 = completionMapper.updateByProjectId(completion);
                    System.out.println("结项阶段更新结果: " + result5);
                    break;
                default:
                    System.out.println("无效的阶段类型: " + phaseType);
                    return false;
            }
            // 只要没有异常就返回true
            return true;
        } catch (Exception e) {
            System.err.println("更新项目阶段信息失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}